package com.example.springsecuritydemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springsecuritydemo.bean.entity.Users;
import com.example.springsecuritydemo.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登录接口
 */
@Service("userDetailsService")
public class LoginService implements UserDetailsService {


    @Autowired
    UsersMapper usersMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

            QueryWrapper<Users> wrapper = new QueryWrapper();
            wrapper.eq("username",username);
            Users users = usersMapper.selectOne(wrapper);
            if(users == null) {
                throw  new UsernameNotFoundException("用户名不存在！");
            }
            System. out .println(users);
            List<GrantedAuthority> auths =
                    AuthorityUtils.
                            commaSeparatedStringToAuthorityList ("admins,ROLE_sale");
        // 第三个参数表示权限
        return new User(username, new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }
}
